import 'package:flutter/services.dart';
import 'dart:io' show Platform;

import 'package:flutter/services.dart';
import 'package:pushy_flutter/pushy_flutter.dart';

import '../../util/_base_export.dart';
import 'app_main.dart';
import '../others/page_upgrade.dart';
import '../others/page_select_wh.dart';
import '../../blocs/product.dart';

class AppFrameView extends StatefulWidget {
  @override
  _AppFrameViewState createState() => _AppFrameViewState();
}

class _AppFrameViewState extends State<AppFrameView> {
  String _deviceToken = 'Loading...';

  @override
  void initState() {
    super.initState();
    // print('Pushy starting');
    initPlatformState();

    // FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  }

  // Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  //   // If you're going to use other Firebase services in the background, such as Firestore,
  //   // make sure you call `initializeApp` before using other Firebase services.
  //   await Firebase.initializeApp();
  //   print("Handling a background message ${message.messageId}");
  // }

  void backgroundNotificationListener(Map<String, dynamic> data) {
    // Print notification payload data
    print('Received notification: $data');

    // Notification title
    String notificationTitle = 'Notification';

    // Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
    String notificationText = data['message'] ?? 'Hello World!';

    // Android: Displays a system notification
    // iOS: Displays an alert dialog
    if ((data['com.google.firebase.auth'] ?? {}).isEmpty)
      Pushy.notify(notificationTitle, notificationText, data);

    // Clear iOS app badge number
    Pushy.clearBadge();
  }

  Future<void> initPlatformState() async {
    // Pushy.listen();
    // Start the Pushy service
    print('Pushy listened');
    // Set custom notification icon (Android)
    Pushy.setNotificationIcon('ic_launcher');
    try {
      // Register the device for push notifications
      String deviceToken = await Pushy.register();

      // Print token to console/logcat
      print('Device token: $deviceToken');
      if (deviceToken.isNotEmpty) AppSession.pushid = deviceToken;
      // Send the token to your backend server
      // ...

      // Update UI with token
      // setState(() {
      //   _deviceToken = deviceToken;
      //   _instruction =
      //       Platform.isAndroid ? '(copy from logcat)' : '(copy from console)';
      // });
    } on PlatformException catch (error) {
      // Print to console/logcat
      print('Error: ${error.message}');

      // Show error
      // setState(() {
      //   _deviceToken = 'Registration failed';
      //   _instruction = '(restart app to try again)';
      // });
    }

    // Listen for push notifications received
    Pushy.setNotificationListener(backgroundNotificationListener);

    // Listen for push notification clicked
    Pushy.setNotificationClickListener((Map<String, dynamic> data) {
      // Print notification payload data
      print('Notification clicked: $data');

      // Extract notification messsage
      // String message = data['message'] ?? 'Hello World!';

      // Display an alert with the "message" payload value
      // showDialog(
      //   context: context,
      //   builder: (BuildContext context) {
      //     return AlertDialog(
      //         title: Text('Notification clicked'),
      //         content: Text(message),
      //         actions: [
      //           FlatButton(
      //             child: Text('OK'),
      //             onPressed: () {
      //               Navigator.of(context, rootNavigator: true).pop('dialog');
      //             },
      //           )
      //         ]);
      //   },
      // );
      // Clear iOS app badge number
      Pushy.clearBadge();
    });
  }

  //// Platform messages are asynchronous, so we initialize in an async method
  // Future<void> initPlatformState() async {
  //   // Start the Pushy service
  //   Pushy.listen();

  //   // Request the WRITE_EXTERNAL_STORAGE permission on Android so that the Pushy SDK will be able to persist the device token in the external storage
  //   if (Platform.isAndroid) {
  //     Pushy.requestStoragePermission();
  //     // Set custom notification icon (Android)
  //     Pushy.setNotificationIcon('ic_notify');
  //   }
  //   try {
  //     print('Device token Ready');
  //     // Register the device for push notifications
  //     String deviceToken = await Pushy.register();
  //     // Print token to console/logcat
  //     print('Device token: $deviceToken');

  //     // Send the token to your backend server
  //     // ...

  //     // Update UI with token
  //     setState(() {
  //       _deviceToken = deviceToken;
  //       // _instruction = Platform.isAndroid ? '(copy from logcat)' : '(copy from console)';
  //     });
  //   } on PlatformException catch (error) {
  //     // Print to console/logcat
  //     print('Failed Platform Error: ${error.message}');
  //     setState(() {
  //       _deviceToken = 'Registration failed';
  //       // _instruction = '(restart app to try again)';
  //     });
  //   } catch (error) {
  //     // Print to console/logcat
  //     print('Failed Error: ${error.message}');
  //   }
  //   // Listen for push notifications
  //   Pushy.setNotificationListener((Map<String, dynamic> data) {
  //     // Print notification payload data
  //     print('Received notifications: $data');

  //     // Clear iOS app badge number
  //     Pushy.clearBadge();

  //     // Extract notification messsage
  //     // String message = data['message'] ?? 'Hello World!';

  //     // Display an alert with the "message" payload value
  //     // showDialog(
  //     //   context: context,
  //     //   builder: (BuildContext context) {
  //     //     return AlertDialog(
  //     //         title: Text('Pushy'),
  //     //         content: Text(message),
  //     //         actions: [
  //     //           FlatButton(
  //     //             child: Text('OK'),
  //     //             onPressed: () {
  //     //               Navigator.of(context, rootNavigator: true).pop('dialog');
  //     //             },
  //     //           )
  //     //         ]);
  //     //   },
  //     // );
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width,
        maxHeight: MediaQuery.of(context).size.height
      ),
      designSize: Size(AppScreen.initWidth, AppScreen.initHeight),
      orientation: Orientation.portrait,
    );

    return MaxScaleTextWidget(
      max: 1.0,
      child: Builder(
        builder: (context) {
          if ((AppSession.packageInfo.version != AppSession.appUtil.last_version) &&
              (AppSession.appUtil.force_update == true))
            return OtherUpgradePage();
          else if (AppSession.wh_id == 0)
            return SelectWhPage();
          else
            return AppMainView();
        },
      ),
    );
  }
}
